<template>
  <div class="survey-container">
    <div v-for="question in questions" :key="question.id" class="questions-container">
      <div class="question">
        <h3>{{ question.title }}</h3>
        <p>{{ question.description }}</p>
      </div>
      <div v-if="question.type === 'radio'">
        <div :id="'pieChart_' + question.id" class="chart-container"></div>
      </div>
      <div v-else-if="question.type === 'checkbox'">
        <div :id="'barChart_' + question.id" class="chart-container"></div>
      </div>
      <div v-else-if="question.type === 'textarea'" class="text-container">
        <el-table
          :data="question.texts.map(text => ({ text }))"
          height="300"
          border
          class="virtualized-table"
          v-loading="loading"
        >
          <el-table-column
            prop="text"
            label="回答列表："
          />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import request from '../../utils/request';
import { ElTable, ElTableColumn } from 'element-plus';

export default {
  components: {
    ElTable,
    ElTableColumn,
  },
  setup() {
    const questions = ref([]);
    const loading = ref(true);
    const id = localStorage.getItem('staticsId');

    onMounted(async () => {
      await getChartData(id);
      questions.value.forEach((question) => {
        if (question.type === 'radio') {
          renderPieChart(question);
        } else if (question.type === 'checkbox') {
          renderBarChart(question);
        }
      });
      loading.value = false;
    });

    const getChartData = async (id) => {
      const config = {
        method: 'get',
        url: 'api/survey/getStatistic',
        params: { id: id },
      };
      try {
        const response = await request(config);
        if (response.code === '200') {
          questions.value = response.data.questions;
          localStorage.removeItem('staticsId');
        } else {
          console.log('Failed to fetch data: ' + response.message);
        }
      } catch (error) {
        console.log('Failed to fetch data: ' + error);
      }
    };

    const renderPieChart = (question) => {
      const pieChart = echarts.init(document.querySelector('#pieChart_' + question.id));
      const data = question.options.map((option) => ({
        value: option.count,
        name: option.text,
      }));
      pieChart.setOption({
        title: {
          text: question.title,
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        series: [
          {
            name: '比例',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      });

      pieChart.on('click', function (params) {
        alert(params.name + ': ' + params.percent + '%');
      });
    };

    const renderBarChart = (question) => {
      const barChart = echarts.init(document.querySelector('#barChart_' + question.id));
      const xAxisData = question.options.map((option) => option.text);
      const seriesData = question.options.map((option) => option.count);
      barChart.setOption({
        title: {
          text: question.title,
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' },
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          name: '选项',
        },
        yAxis: {
          name: '选择次数',
        },
        series: [
          {
            type: 'bar',
            data: seriesData,
            itemStyle: {
              color: '#5470c6',
              barBorderRadius: [5, 5, 0, 0],
            },
            barWidth: '50%',
          },
        ],
      });
    };

    return {
      id,
      questions,
      loading,
    };
  },
};
</script>

<style>
@import 'element-plus/dist/index.css';

.survey-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.questions-container {
  margin-bottom: 30px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 20px;
}

.question h3 {
  font-size: 20px;
  color: #333;
}

.question p {
  font-size: 16px;
  color: #666;
}

.chart-container {
  height: 300px;
  margin-top: 20px;
}

.text-container {
  margin-top: 10px;
  padding-left: 20px;
}

.virtualized-table {
  height: 300px;
  margin-top: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  overflow: hidden;
}
</style>
